package org.cnc.rmi.interfaces;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.ServerNotActiveException;
 
@SuppressWarnings("serial")
public class RmiServer extends java.rmi.server.UnicastRemoteObject
{
	String name;
	int port;
	Registry registry;    // rmi registry for lookup the remote objects.
	
	public RmiServer( String name, int port ) throws RemoteException
    {
		this.name = name;
		this.port = port;
		
        try{

            // get the address of this host.
        	String address = (InetAddress.getLocalHost()).toString();

        	if ( port == 0 )
        		port = 3232;
       
        	System.out.println(name + " : this address="+address+",port="+port);
 
	        // create the registry and bind the name and object.
	        registry = LocateRegistry.createRegistry( port );
            registry.rebind(name, this);
        }
        catch(Exception e)
        {
            throw new RemoteException(name + " : " + e.getMessage());
        }
    }
	
	public void rebind( String name, int port ) throws RemoteException
	{
		if ( this.port != port )
		{
			registry = LocateRegistry.createRegistry(port);
			System.out.println(name + " : port="+port);
			this.port = port;
		}
		
		registry.rebind(name, this);
		this.name = name;
	}
	public void unbind()
	{
		try
		{
			registry.unbind(name);
		} catch ( Exception e )
		{
			e.printStackTrace();
		}
	}
	
	public String getStatus()
	{
		String client, server;

		client = "Client: " + getClientAddress();
		
		try {
			server = "Started at: " + (InetAddress.getLocalHost()).toString() + ". ";
		} catch (UnknownHostException e1) {
			server = "Stopped.";
		}
		
		return server + " " + client;
	}
	
	public int getPort()
	{
		return this.port;
	}
	
	public String getName()
	{
		return this.name;
	}
	
	public String getClientAddress()
	{
		try {
			return getClientHost();
		} catch (ServerNotActiveException e) {
			return "";
		}
	}
}
